package com.example.demo.config;

import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

/**
 * @Description: 使用线程池进行并发测试和海量请求测试
 * @author: liyuan
 * @data 2020-12-17 10:38
 */
@Component
//@EnableAsync
public class MyThreadPoolConfig {
    @Bean(name = "simpleThreadPoolTaskExecutor")
    public ThreadPoolTaskExecutor defaultThreadPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程数目
        executor.setCorePoolSize(16);
        //指定最大线程数
        executor.setMaxPoolSize(128);
        //队列中最大的数目
        executor.setQueueCapacity(16);
        //线程空闲后的最大存活时间
        executor.setKeepAliveSeconds(60);
        //线程名称前缀
        executor.setThreadNamePrefix("executorService-");
        //允许线程空闲时间（单位：默认为秒;可以不设置
        executor.setAwaitTerminationSeconds(60);
        // 设置 shutdown 时先等待所有任务处理完，可以不设置
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //rejection-policy：当pool已经达到max size的时候，如何处理新任务 //CALLER_RUNS：不在新线程中执行任务，而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //加载
        executor.initialize();
        return executor;
    }
}
//使用 ，在方法上添加 @Async("simpleThreadPoolTaskExecutor")即可，博客地址
// https://www.cnblogs.com/monkay/p/11170421.html
